
package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.constants.GlobalConstants;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 创建日期: 2022/05/19 09:56
 *
 * @author shuyang
 */
@Slf4j
@Service
public class ICartServiceImpl implements ICartService {
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    RedissonClient redissonClient;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            String userKey = GlobalConstants.CART_ITEM_CACHE_PREFIX + userId;
            // Config config = new Config();
            // SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
            // RedissonClient redissonClient = Redisson.create(config);
            RMap<Long, CartProductDto> map = redissonClient.getMap(userKey);
            Set<Map.Entry<Long, CartProductDto>> entries = map.entrySet();
            ArrayList<CartProductDto> list = new ArrayList<>();
            for (Map.Entry<Long, CartProductDto> entry : entries) {
                list.add(entry.getValue());
            }
            cartListByIdResponse.setCartProductDtos(list);
            cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.getCartListById occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(cartListByIdResponse, e);
        }
        return cartListByIdResponse;
    }


    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse addCartResponse = new AddCartResponse();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            Integer num = request.getNum();
            Long itemId = request.getItemId();
            Item item = itemMapper.selectByPrimaryKey(itemId);
            String image = item.getImage();
            String[] cartImage = image.split(",");
            CartProductDto cartProductDto = new CartProductDto(itemId, item.getPrice(), (long) num, (long) item.getLimitNum(), GlobalConstants.CART_ITEM_CACHE_DEFAULT, item.getTitle(), cartImage[0]);
            String userKey = GlobalConstants.CART_ITEM_CACHE_PREFIX + userId;
            // Config config = new Config();
            // config.useSingleServer().setAddress("redis://localhost:6379");
            // RedissonClient redissonClient = Redisson.create(config);
            RMap<Long, CartProductDto> map = redissonClient.getMap(userKey);
            map.put(itemId, cartProductDto);
            addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.addToCart occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(addCartResponse, e);
        }

        return addCartResponse;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse updateCartNumResponse = new UpdateCartNumResponse();
        try {
            String checked = request.getChecked();
            Long itemId = request.getItemId();
            Integer num = request.getNum();
            Long userId = request.getUserId();
            String userKey = GlobalConstants.CART_ITEM_CACHE_PREFIX + userId;
            RMap<Long, CartProductDto> map = redissonClient.getMap(userKey);
            CartProductDto cartProductDto = map.get(itemId);
            cartProductDto.setChecked(checked);
            cartProductDto.setProductNum((long) num);
            map.put(itemId, cartProductDto);
            updateCartNumResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            updateCartNumResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.updateCartNum occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(updateCartNumResponse, e);
        }

        return updateCartNumResponse;
    }
    /*
     * @author 孙豪骏
     * @date   2022/05/19 12:17
     * @param request
     * @return com.cskaoyan.shopping.dto.CheckAllItemResponse
     * @Description 全选或者反全选
     */
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        request.requestCheck();
        String checked = request.getChecked();
        Long userId = request.getUserId();
        RMap<Object, Object> userCart = redissonClient.getMap(GlobalConstants.CART_ITEM_CACHE_PREFIX + userId);
        Set<Map.Entry<Object, Object>> cartEntrys = userCart.entrySet();
        for (Map.Entry<Object, Object> cartEntry : cartEntrys) {
            CartProductDto cartProductDto = (CartProductDto) cartEntry.getValue();
            cartProductDto.setChecked(checked);
            Object key = cartEntry.getKey();
            userCart.put(key, cartProductDto);
        }
        CheckAllItemResponse checkAllItemResponse = new CheckAllItemResponse();
        checkAllItemResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        checkAllItemResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return checkAllItemResponse;
    }


    /*删除购物车的项目
     * @author 孙豪骏
     * @date `2022/05/19` 8:31
     * @param request
     * @return com.cskaoyan.shopping.dto.DeleteCartItemResponse
     * @Description  删除购物车
     */
    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();
        request.requestCheck();
        String userId = String.valueOf(request.getUserId());
        // String productId = String.valueOf(request.getItemId());
        RMap<Object, Object> userCart = redissonClient.getMap(GlobalConstants.CART_ITEM_CACHE_PREFIX + userId);
        //从redis 库中移除 所对应PRODUICTID的东西
        Object remove = userCart.remove(request.getItemId());
        if (remove != null) {
            deleteCartItemResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            deleteCartItemResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            return deleteCartItemResponse;
        }
        deleteCartItemResponse.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
        deleteCartItemResponse.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
        return deleteCartItemResponse;
    }


    /*  * @author 孙豪骏
     * @date   2022/05/19 8:32
     * @param request
     * @return com.cskaoyan.shopping.dto.DeleteCheckedItemResposne
     * @Description  删除购物车所选
     */
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        request.requestCheck();
        DeleteCheckedItemResposne deleteCheckedItemResposne = new DeleteCheckedItemResposne();
        RMap<Object, Object> userCart = redissonClient.getMap(GlobalConstants.CART_ITEM_CACHE_PREFIX + request.getUserId());
        //将这个人对应的map转换成集合便利
        Set<Map.Entry<Object, Object>> entries = userCart.entrySet();
        for (Map.Entry<Object, Object> entry : entries) {
            CartProductDto cartProductDto = (CartProductDto) entry.getValue();
            if (cartProductDto.getChecked().equals("true")) {
                log.info("删除有效信息用户的所选购物车为产品id为{}", entry.getKey());
                userCart.remove(entry.getKey());
            }
        }
        deleteCheckedItemResposne.setCode(SysRetCodeConstants.SUCCESS.getCode());
        deleteCheckedItemResposne.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return deleteCheckedItemResposne;
    }


    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse clearCartItemResponse = new ClearCartItemResponse();
        try {
            request.requestCheck();
            List<Long> productIds = request.getProductIds();
            Long userId = request.getUserId();
            String userKey = GlobalConstants.CART_ITEM_CACHE_PREFIX + userId;
            RMap<Long, CartProductDto> map = redissonClient.getMap(userKey);
            for (Long productId : productIds) {
                map.remove(productId);
            }
            clearCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            clearCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.clearCartItemByUserID occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(clearCartItemResponse, e);
        }
        return clearCartItemResponse;
    }
}

